package com.zheng.redpacket.server.controller.rabbitmq;

import com.google.common.base.Strings;
import com.zheng.redpacket.api.CommonResult;
import com.zheng.redpacket.api.ResultCode;
import com.zheng.redpacket.server.dto.UserLoginDto;
import com.zheng.redpacket.server.dto.UserRegDto;
import com.zheng.redpacket.server.serivce.UserRegService;
import com.zheng.redpacket.server.serivce.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/user")
public class UserController {
    private static Logger LOGGER = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;
    @Autowired
    private UserRegService userRegService;

    @PostMapping("/login")
    public CommonResult login(@RequestBody @Validated UserLoginDto dto, BindingResult result) {
        if (result.hasErrors()) {
            return new CommonResult(ResultCode.VALIDATE_FAILED);
        }
        try {
            Boolean login = userService.login(dto);
            if (login) {
                return CommonResult.success(login);
            }else {
                return CommonResult.failed(ResultCode.FAILED,"账号密码不正确");
            }
        }catch (Exception e) {
            return CommonResult.failed(ResultCode.FAILED, e.getMessage());
        }
    }

    @PostMapping("/registry")
    public CommonResult userReg(UserRegDto dto) {
        if (Strings.isNullOrEmpty(dto.getUserName()) || Strings.isNullOrEmpty(dto.getPassword())) {
            return CommonResult.failed("用户名密码不能为空");
        }
        try {
            userRegService.userReg(dto);
            return CommonResult.success("注册成功");
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @PostMapping("/zkRegistry")
    public CommonResult reg(UserRegDto dto) {
        if (Strings.isNullOrEmpty(dto.getUserName()) || Strings.isNullOrEmpty(dto.getPassword())) {
            return CommonResult.failed("用户名密码不能为空");
        }
        try {
            userRegService.userRegLockByZkLock(dto);
            return CommonResult.success("注册成功");
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }

    @GetMapping("/submit")
    public CommonResult lockReg(UserRegDto dto) {
        if (Strings.isNullOrEmpty(dto.getUserName()) || Strings.isNullOrEmpty(dto.getPassword())) {
            return CommonResult.failed("请输入账号或密码");
        }
        try {
            userRegService.userRegLockByRedisson(dto);
            return CommonResult.success("注册成功");
        } catch (Exception e) {
            return CommonResult.failed(e.getMessage());
        }
    }
}
